import yfinance as yf
import pandas as pd
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

# 1. 下载数据
# 选择一只股票，例如苹果 AAPL
stock = 'AAPL'
start_date = '2010-01-01'
end_date = '2023-12-31'

# 获取股票价格
aapl = yf.download(stock, start=start_date, end=end_date)['Adj Close']
# 获取标普500作为市场指数
sp500 = yf.download('^GSPC', start=start_date, end=end_date)['Adj Close']
# 获取无风险利率（使用10年期国债收益率近似）
risk_free = yf.download('^TNX', start=start_date, end=end_date)['Adj Close']
# 注意：^TNX 是年化收益率（百分比），需转换为日度无风险利率
risk_free = (1 + risk_free / 100) ** (1/252) - 1  # 近似日无风险利率

# 计算日收益率
ret_aapl = aapl.pct_change().dropna()
ret_sp500 = sp500.pct_change().dropna()

# 对齐日期
data = pd.concat([ret_aapl, ret_sp500, risk_free], axis=1)
data.columns = ['stock_ret', 'market_ret', 'rf']
data = data.dropna()

# 计算超额收益
data['excess_ret'] = data['stock_ret'] - data['rf']
data['market_excess'] = data['market_ret'] - data['rf']

# 2. CAPM 回归
X_capm = sm.add_constant(data['market_excess'])
model_capm = sm.OLS(data['excess_ret'], X_capm).fit()
print("=== CAPM 回归结果 ===")
print(model_capm.summary())
